<?php
class CV_ORM_Schema_Reader_MySQL{
	protected $pdo;
	protected $schema = array();
	function __construct( $pdo ){
		$this->pdo = $pdo;
		$table = $this->pdo->query( "SELECT table_schema, table_name, column_name,column_key FROM information_schema.columns WHERE table_schema ='kalender' AND table_schema != 'information_schema'" )->fetchAll();
		foreach( $table as $record ){
			$this->schema['databases'][$record['table_schema']]['tables'][$record['table_name']]['columns'][] = $record['column_name'];
			if( isset($record["column_key"]) && $record["column_key"] === "PRI" ){
				$this->schema['databases'][$record['table_schema']]['tables'][$record['table_name']]['primary_key'][] = $record['column_name'];
			}
			$this->schema['databases'][$record['table_schema']]['tables'][$record['table_name']]['records'][] = $record;
		}
		$x = 1;
	}
	public function getDatabaseNames(){
		return array_keys($this->schema['databases']);
	}
	public function getTableNames( $database ){
		return array_keys($this->schema['databases'][$database]['tables']);
	}
	public function getColumnNames( $database, $table ){
		return $this->schema['databases'][$database]['tables'][$table]['columns'];
	}
	public function getPrimaryKey( $database, $table ){
		if(isset($this->schema['databases'][$database]['tables'][$table]['primary_key'])){
			$key = $this->schema['databases'][$database]['tables'][$table]['primary_key'];
			if(count($key) > 1){
				throw new Exception('multi-field primary key not supported');
			}
			return array_pop($key);
		} else {
			return NULL;
		}
	}
	/*public function getFieldRecord( $database, $table, $column ){
		return lc( '$x for $x in $schema if $x["table_schema"] === $database && $x["table_name"] === $table && $x["column_name"] === $column', array('schema'=>$this->schema,'database'=>$database,'table'=>$table,'column'=>$column));
	}*/
}